package controllers;

import helpers.StringHelper;
import helpers.UrlHelper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class NetworkToolServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		TreeMap<String, String> check = new TreeMap<String, String>();
		response.setHeader( "Cache-Control", "public, max-age=86400");
		response.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		String name = (String) request.getParameter("domain");
		String type = (String) request.getParameter("type");
		String result = "";
		
		if (name == null || !UrlHelper.checkDomain(name)) {
			check.put("name", "Please provice your domain.");
		} else {
			name = UrlHelper.getMainDomain(name);
		} 
		
		if (type == null || type.isEmpty()) {
			type = "ping";
			check.put("type", "Please choise a tool.");
		}
		
		if (check.size() == 0) {
			try {
				response.setHeader( "Cache-Control", "public, max-age=86400");
				response.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
				
				URL dataURL = new URL("http://network-tools.com/default.asp?prog="+type+"&host="+name);

				BufferedReader reader = new BufferedReader(new InputStreamReader(
						dataURL.openStream(), Charset.forName("UTF-8")));
				String content = "";
				char[] buf = new char[102102];
				int numRead=0;
		        while((numRead=reader.read(buf)) != -1){
		            String readData = String.valueOf(buf, 0, numRead);
		            content += readData;
		            buf = new char[102102];
		        }
		        reader.close();

				Document doc = Jsoup.parse(content);
				doc.select("center").remove();
				result = doc.select("div[style=width:680px; float:left; margin-top:25px;]").get(0).html();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		request.setAttribute("result", StringHelper.cleanContent(result));
		request.setAttribute("name", name);
		request.setAttribute("type", type);
		request.setAttribute("check", check);
		try {
			request.getRequestDispatcher("/pages/network_tool.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
}
